package io.acna.basedao.mybatis.service.impl;

import io.acna.basedao.mybatis.core.QueryCondition;
import io.acna.basedao.mybatis.dao.IBaseMapper;
import io.acna.basedao.mybatis.plugin.QueryUtil;
import io.acna.basedao.mybatis.service.IBaseService;
import io.acna.basedao.mybatis.util.MyBatisExcepUtil;
import io.acna.basedao.mybatis.util.MyBatisReflectUtil;

import java.util.List;

import com.github.pagehelper.Page;

public abstract class BaseService<T> implements IBaseService<T> {

	private final IBaseMapper baseDao;
	private final String columnName;
	private final String fieldIdName;

	public BaseService(IBaseMapper baseDao, String columnName,
			String fieldIdName) {
		this.baseDao = baseDao;
		this.columnName = columnName;
		this.fieldIdName = fieldIdName;
	}

	@Override
	public T findByName(String name) {
		QueryCondition c = QueryUtil.createCondition();
		c.addSearchContions(columnName, name);
		c.isQueryAll();
		Page<T> es = baseDao.searchList(c.getRowBound(), c);
		if (es.getTotal() <= 0)
			MyBatisExcepUtil.newNotFound(columnName + ":" + name);
		return es.getResult().get(0);
	}

	@Override
	public T findById(long id) {
		return (T) baseDao.selectByPrimaryKey(id);
	}

	@Override
	public Page<T> findList(QueryCondition condition) {
		if (condition == null) {
			condition = QueryUtil.createCondition();
			condition.isQueryAll();
		}
		return baseDao.searchList(condition.getRowBound(), condition);
	}

	@Override
	public T findUnique(QueryCondition condition) {
		condition.isQueryAll();
		List<T> es = findList(condition);
		if (es.size() > 0)
			return es.get(0);
		return null;
	}

	@Override
	public Long save(T entity) {
		baseDao.insertSelective(entity);
		return (Long) MyBatisReflectUtil.getFieldValue(entity, fieldIdName);

	}

	@Override
	public Long update(T entity) {
		baseDao.updateByPrimaryKeySelective(entity);
		return (Long) MyBatisReflectUtil.getFieldValue(entity, fieldIdName);

	}

	@Override
	public void remove(long id) {
		baseDao.deleteByPrimaryKey(id);
	}

	@Override
	public Page<T> findAll() {
		return findList(QueryUtil.createConditionQueryAll());
	}
}
